package com.vitabuybuy.tv.ui

import android.app.ActivityManager
import android.content.Context
import android.os.Bundle
import android.view.View
import com.library.common.base.BaseActivity
import com.library.common.base.appContext
import com.library.common.dto.MessageEvent
import com.library.common.ext.mmkv

import com.vitabuybuy.tv.R
import com.vitabuybuy.tv.databinding.ActivityMainBinding
import com.library.common.toast.XToast
import com.library.common.util.AppManager
import com.library.common.util.FragmentUtils
import com.library.common.net.HeadInterceptor
import com.library.common.util.MMKVContancts
import com.vitabuybuy.tv.ui.auth.LoginActivity
import com.vitabuybuy.tv.ui.cart.CartFragment
import com.vitabuybuy.tv.ui.home.HomeFragment
import com.vitabuybuy.tv.ui.mine.MineFragment
import com.vitabuybuy.tv.ui.shopcenter.ShopCenterFragment
import com.vitabuybuy.tv.ui.tencent.liveroom.IMLVBLiveRoomListener
import com.vitabuybuy.tv.ui.tencent.liveroom.MLVBLiveRoom
import com.vitabuybuy.tv.ui.viewmodel.MainViewModel
import com.vitabuybuy.tv.utils.EventCode

import kotlinx.android.synthetic.main.activity_main.*
import kotlin.system.exitProcess

class MainActivity : BaseActivity<MainViewModel, ActivityMainBinding>() {
    override val isUseBaseTitleBar: Boolean
        get() = false
    override val layoutId: Int
        get() = R.layout.activity_main

    private var lastTimePressed: Long = 0

    override fun initView(savedInstanceState: Bundle?) {
        showCurrentFragment(0)
    }

    override fun onResume() {
        super.onResume()
        if (mmkv.decodeBool(MMKVContancts.IS_LOGIN_IN, false)) {
            clNoLogin.visibility = View.GONE
        } else {
            clNoLogin.visibility = View.VISIBLE
        }
    }

    override fun onEvent(event: MessageEvent) {
        when (event.code) {//退出登录---用户未登录---
            EventCode.login_out -> {
                MLVBLiveRoom.sharedInstance(appContext).logout()
                //清除本地数据
                HeadInterceptor.sessionId = ""
                mmkv.remove(MMKVContancts.IS_LOGIN_IN)
                mmkv.remove(MMKVContancts.USER_ID)
                mmkv.remove(MMKVContancts.USER_SIGN)
                mmkv.remove(MMKVContancts.SESSIONID)
                mmkv.remove(MMKVContancts.USER_PHONE)
                mmkv.remove(MMKVContancts.IS_LOGIN_IN)
                mmkv.remove(MMKVContancts.USER_EMAIL)
                //切换到首页模块
                navView.selectedItemId = R.id.navigationHome
//                显示登录按钮点击
                clNoLogin.visibility = View.VISIBLE
//              ShareSDK.getPlatform(Wechat.NAME).removeAccount(true)
                //关闭所有页面，除首页外
                AppManager.get().finishActivitiesWithoutTarget(MainActivity::class.java)
            }
            EventCode.jump_to_mine -> {
                navView.selectedItemId = R.id.navigationMine
            }
            EventCode.jump_login -> {
                LoginActivity.openActivity(mContext)
            }
        }
    }

    override fun eventHandling() {
        navView.setOnNavigationItemSelectedListener { menuItem ->
            when (menuItem.itemId) {
                R.id.navigationHome -> {
                    showCurrentFragment(0)
                    return@setOnNavigationItemSelectedListener true
                }
                R.id.navigationCommodityCenter -> {
                    showCurrentFragment(1)
                    return@setOnNavigationItemSelectedListener true
                }
                R.id.navigationShoppingCart -> {
                    if (!mmkv.decodeBool(MMKVContancts.IS_LOGIN_IN, false)) {
                        LoginActivity.openActivity(mContext)
                        return@setOnNavigationItemSelectedListener false
                    }
                    showCurrentFragment(2)
                    return@setOnNavigationItemSelectedListener true
                }
                R.id.navigationMine -> {
                    if (!mmkv.decodeBool(MMKVContancts.IS_LOGIN_IN, false)) {
                        LoginActivity.openActivity(mContext)
                        return@setOnNavigationItemSelectedListener false
                    }
                    showCurrentFragment(3)
                    return@setOnNavigationItemSelectedListener true
                }
            }
            false
        }
        btnLogin.setOnClickListener {
            LoginActivity.openActivity(mContext)
        }
    }

    private fun showCurrentFragment(index: Int) {
        when (index) {
            0 -> FragmentUtils.replaceFragment(
                supportFragmentManager,
                R.id.containerFragment,
                HomeFragment::class.java.name
            )
            1 -> FragmentUtils.replaceFragment(
                supportFragmentManager,
                R.id.containerFragment,
                ShopCenterFragment::class.java.name
            )
            2 -> FragmentUtils.replaceFragment(
                supportFragmentManager,
                R.id.containerFragment,
                CartFragment::class.java.name
            )
            3 -> FragmentUtils.replaceFragment(
                supportFragmentManager,
                R.id.containerFragment,
                MineFragment::class.java.name
            )
        }
    }

    override fun onBackPressed() {
        if (System.currentTimeMillis() - lastTimePressed < 1000) {
            exitProcess(0)
        } else {
            lastTimePressed = System.currentTimeMillis()
            XToast.normal("再按一次退出程序")
        }
    }


    /**
     * 判断某个页面是不是在第一个页面
     *
     * @param context
     * @param className
     * @return
     */
    private fun isActivityTop(
        context: Context,
        className: String
    ): Boolean {
        val am =
            context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val activityName = am.getRunningTasks(1)[0].topActivity!!.className
        return try {
            val classObject = Class.forName(activityName)
            classObject.simpleName == className
        } catch (e: ClassNotFoundException) {
            e.printStackTrace()
            false
        }
    }

    companion object {
        fun openActivity(mContext: BaseActivity<*, *>) {
            mContext.startActivity(null, MainActivity::class.java)
        }
    }
}